const { uploadDir, readData, pushLog } = require('../common/operate');
var { APIOK, APIError } = require('../common/status');
var fs = require('fs');
var path = require('path');

var fn_rmdir = async (ctx, next) => {
    let token = ctx.headers.mytoken || false
    if (readData(ctx.params.id) == token) {
        if (ctx.params.id && ctx.params.time) {
            let dirPath = path.join(uploadDir, `/${ctx.params.id}/${ctx.params.time}`)
            try {
                deleteall(dirPath)
                pushLog(ctx.params.id, ctx.params.time, 0, '删除目录', '成功')
                APIOK(ctx, 'ok')
            } catch (e) {
                pushLog(ctx.params.id, ctx.params.time, 0, '删除目录', '失败')
                APIError(ctx, 404, '删除失败')
            }
        } else {
            APIError(ctx, 400, '参数错误')
        }
    } else {
        pushLog(ctx.params.id, ctx.params.time, 0, '删除目录', '权限不通过')
        APIError(ctx, 403, '权限不通过')
    }
}

function deleteall(path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach((file) => {
            var curPath = path + "/" + file;
            fs.unlinkSync(curPath);
        });
        fs.rmdirSync(path);
    } else {
        throw 404
    }
};

module.exports = fn_rmdir